package com.lagou.rpc.consumer.loadbalance.impl;

import com.lagou.rpc.consumer.loadbalance.AbstractLoadBalance;
import com.lagou.rpc.zookeeper.metrics.RequestMetrics;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MinCostLoadBalance extends AbstractLoadBalance {
    @Override
    protected String doSelect(List<String> list) {
        if(list.size() == 0){
            return null;
        }

        String connectStirng = "";

        List<RequestMetrics.Metrics> allInstances = RequestMetrics.getInstance().getAllInstances();
        if (CollectionUtils.isEmpty(allInstances)) {
            //随机获取一个
            connectStirng = new RandomLoadBalance().doSelect(list);
        }

        //请求记录次没有实际服务端多，说明还有没被请求过的服务端
        if (list.size()> allInstances.size()) {
            //还是随机返回一个
            connectStirng =  new RandomLoadBalance().doSelect(list);
        }else {
            //所有的都被请求过了，开始使用按服务响应时间短的优先
            Collections.sort(allInstances, new Comparator<RequestMetrics.Metrics>() {

                @Override
                public int compare(RequestMetrics.Metrics o1, RequestMetrics.Metrics o2) {
                    return Long.compare(o1.getCost(), o2.getCost());
                }

            });

            //获取耗费时间最少的服务端
            RequestMetrics.Metrics metrics0 = allInstances.get(0);

            connectStirng = list.stream().filter(stirng ->
                    stirng.equals(metrics0.getIp() + ":" + metrics0.getPort())).collect(Collectors.toList()).get(0);
        }
        return connectStirng;

    }
}
